﻿using Che.AppService.AppService.Login;
using Che.Domain.Entity.Che.User;
using Che.Domain.repository;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using SqlSugar;
using System.Text.Json;

namespace Che.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly APPILogin iu;
        private readonly ILogger<LoginController> _logger;
        private readonly IDistributedCache distributedCache;
        public ISqlSugarClient client { get; set; }
        
        public LoginController(APPILogin iu, ILogger<LoginController> logger, ISqlSugarClient client , IDistributedCache distributedCache)
        {
            this.distributedCache = distributedCache;
            this.iu = iu;
            _logger = logger;   
            this.client = client;
        }

        /// <summary>
        /// 测试数据库连接并将数据存入 Redis
        /// </summary>
        [HttpGet("test")]
        public async Task<IActionResult> TestConnetion()
        {
            const string cacheKey = "users_cache_key"; // Redis 缓存键

            // 1. 尝试从 Redis 中获取数据
            var cachedData = await distributedCache.GetStringAsync(cacheKey);
            if (!string.IsNullOrEmpty(cachedData))
            {
                // 如果缓存中存在数据，直接返回
                var usersFromCache = JsonSerializer.Deserialize<List<User>>(cachedData);
                return Ok(usersFromCache);
            }

            // 2. 如果缓存中没有数据，从数据库中查询
            var users = client.Queryable<User>().ToList();

            // 3. 将查询到的数据存入 Redis
            var serializedData = JsonSerializer.Serialize(users);
            await distributedCache.SetStringAsync(cacheKey, serializedData, new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) // 设置缓存过期时间为 10 分钟
            });

            // 4. 返回查询到的数据
            return Ok(users);
        }
        /// <summary>
        /// 登陆方法(初始版本待优化)
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost("login")]
        public async Task<IActionResult> Login([FromBody] User user)
        {
            try
            {
                if (user == null || string.IsNullOrEmpty(user.UserName) || string.IsNullOrEmpty(user.Userpwd))
                {
                    return BadRequest("用户名和密码不能为空");
                }

                // 调用服务层进行登录验证
                var result = await iu.Logins(user);

                if (result == null)
                {
                    return Unauthorized("用户名或密码错误");
                }

                // 登录成功，返回用户信息
                return Ok(result);
            }
            catch (Exception ex)
            {
                // 记录日志
                return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
            }
        }
        [HttpPost("register")]
        public async Task<bool> Register([FromBody] User user) 
        {
            try
            {
                var e = await iu.Register(user);
                // 返回注册结果
                return e;
            }
            catch (Exception ex)
            {
                // 记录错误日志
                _logger.LogError(ex, "注册失败");
                return false;
            }
        }
    }
}
